package pers.mobian.aop;

import org.aopalliance.aop.Advice;
import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
import org.springframework.aop.*;
import org.springframework.aop.framework.ProxyFactory;
import org.springframework.aop.support.StaticMethodMatcherPointcut;
import pers.mobian.springfirst.firstTest.User;

import java.lang.reflect.Method;

/**
 * @Date 2021/10/8 21:04
 * @Created mobian
 * @Description
 */
public class ProxyFactoryTest {
	public static void main(String[] args) {

		// 创建被代理的对象
		UserService service = new UserServiceImpl();

		// 创建一个ProxyFactory对象
		ProxyFactory factory = new ProxyFactory();

		// 设置被代理的对象
		factory.setTarget(service);

		// 添加代理的逻辑: 方法调用前、方法调用后、方法发生异常后
		factory.addAdvice(new MoBeforeAdvice());
		factory.addAdvice(new MoAfterAdvice());
		factory.addAdvice(new MoThrowsAdvice());

		// 进行对应的方法调用
		// 类似于jdk动态代理的invoke方法 Cglib动态代理的intercept方法
		factory.addAdvice(new MethodInterceptor() {
			@Override
			// 注意: 此处的MethodInvocation是aop包下的
			// 和cglib动态代理所使用的MethodInvocation类不是同一个包下的
			public Object invoke(MethodInvocation invocation) throws Throwable {
				System.out.println("方法调用----前");
				// invocation 代理后的对象
				Object proceed = invocation.proceed();
				System.out.println("方法调用----后");
//				throw new NullPointerException("抛出一个空指针异常");
				return null;
			}
		});

		UserService proxy = (UserService) factory.getProxy();
		proxy.show();
	}
}
